package com.example.state.machine.service.impl;

import com.example.state.machine.entity.Ticket;
import com.example.state.machine.enums.TicketEvent;
import com.example.state.machine.enums.TicketState;
import com.example.state.machine.service.TicketService;
import jakarta.annotation.Resource;
import org.springframework.statemachine.StateMachine;
import org.springframework.statemachine.config.StateMachineFactory;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class TicketServiceImpl implements TicketService {

    private final Map<Long, Ticket> ticketMap = new ConcurrentHashMap<>();

    @Resource
    private StateMachineFactory<TicketState, TicketEvent> stateMachineFactory;

//    @Resource
//    private TicketRepository ticketRepository;  // 数据库操作


    // 创建工单（初始状态为CREATED）
    public Ticket createTicket(String description) {
        Ticket ticket = new Ticket();
        ticket.setDescription(description);
        ticket.setState(TicketState.CREATED);
        ticketMap.put(ticket.getTicketId(), ticket);
        return ticket;
        // return ticketRepository.save(ticket);    // 数据库操作
    }

    // 处理工单（状态机触发）
    public void processTicket(Long ticketId, String operator, String operatorName) {
        Ticket ticket = ticketMap.get(ticketId);
        if (ticket == null) {
            throw new IllegalArgumentException("工单不存在");
        }

        if (ticket.getState() == TicketState.PROCESSING) {
            throw new IllegalStateException("工单正在处理中，请勿重复处理");
        }

        ticket.setOperator(operator);
        ticket.setOperatorName(operatorName);
        ticket.setState(TicketState.PROCESSING);
    }

    // 关闭工单（状态机触发）
    public void closeTicket(Long ticketId, String feedback, String remark) {
        Ticket ticket = ticketMap.get(ticketId);
        if (ticket == null) {
            throw new IllegalArgumentException("工单不存在");
        }

        if (ticket.getState() != TicketState.PROCESSING) {
            throw new IllegalStateException("工单状态不正确，无法关闭");
        }

        ticket.setFeedback(feedback);
        ticket.setRemark(remark);
        ticket.setState(TicketState.CLOSED);
    }

    // 查询工单
    public Ticket getTicket(Long ticketId) {
        Ticket ticket = ticketMap.get(ticketId);
        if (ticket == null) {
            throw new IllegalArgumentException("工单不存在");
        }
        return ticket;
    }

    // 触发工单事件
    public void triggerEvent(Long ticketId, TicketEvent event) {
        StateMachine<TicketState, TicketEvent> stateMachine = stateMachineFactory.getStateMachine(ticketId.toString());
        stateMachine.start();

        try {
            if (stateMachine.sendEvent(event)) {
                // 持久化状态
                Ticket ticket = ticketRepository.findById(ticketId).orElseThrow();
                ticket.setState(stateMachine.getState().getId());
                ticketRepository.save(ticket);
            }
        } finally {
            stateMachine.stop();
        }
    }

}
